package com.kaibo.retrofit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.time.Duration;

/**
 * @author: kaibo
 * @date: 2021/1/13 18:29
 * @GitHub: https://github.com/yuxuelian
 * @qq: 568966289
 * @description:
 */

public class RetrofitFactoryBean<T> implements FactoryBean<T>, ApplicationContextAware {

    private final Class<T> retrofitInterface;
    private final RetrofitClient retrofitClient;
    private RetrofitProperties retrofitProperties;
    private OkHttpClient okHttpClient;

    public RetrofitFactoryBean(Class<T> retrofitInterface) {
        this.retrofitInterface = retrofitInterface;
        this.retrofitClient = retrofitInterface.getAnnotation(RetrofitClient.class);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        RetrofitProperties temp = applicationContext.getBean(RetrofitProperties.class);
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .readTimeout(Duration.ofSeconds(10L))
                .writeTimeout(Duration.ofSeconds(10L))
                .connectTimeout(Duration.ofSeconds(10L));
        if (temp.getLogEnable()){
            builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                    .addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));

        }
        this.retrofitProperties = temp;
        this.okHttpClient = builder.build();
    }

    @Override
    public T getObject() throws Exception {
        String baseUrl1 = retrofitClient.baseUrl();
        String baseUrl2 = retrofitClient.value();
        String baseUrl3 = retrofitProperties.getMasterHost();
        String baseUrl;
        if (baseUrl1.isEmpty()) {
            if (baseUrl2.isEmpty()) {
                if (baseUrl3.isEmpty()) {
                    baseUrl = "";
                } else {
                    baseUrl = baseUrl3;
                }
            } else {
                baseUrl = baseUrl2;
            }
        } else {
            baseUrl = baseUrl1;
        }
        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient).build()
                .create(retrofitInterface);
    }

    @Override
    public Class<?> getObjectType() {
        return retrofitInterface;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
